<?php

namespace App\Http\Controllers;

use Illuminate\Foundation\Bus\DispatchesJobs;
use Illuminate\Http\Request;
use Illuminate\Routing\Controller as BaseController;
use Illuminate\Foundation\Validation\ValidatesRequests;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Log;

//header("Access-Control-Allow-Origin: *");
//header("Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Authorization, We-Token");

class Controller extends BaseController
{
    use AuthorizesRequests, DispatchesJobs, ValidatesRequests;

    // 接口返回字段
    protected $return = ["code" => 0, "msg" => 'success', 'data' => []];

    // 接收的全部参数，类型为数组
    protected $all = [];

    // 接口用户信息[object]
    protected $userInfo;

    // 当前访问的路由
    private $uri = '';

    // 返回值可以被过滤不记录的路由
    private $returnLogFliters = [
//        'api/admin/right/user_right', // 用户界面权限
//        'api/common/get/dict_data', // dict_type记录
//        'api/common/app_config', // 公共查询部分
    ];


    /**
     * 构造函数用来接受参数，方便使用
     * @param Request $request
     */
    public function __construct(Request $request)
    {

        // 以数组形式获取全部参数
        $this->all = $request->all();

        // 获取用户信息
        $this->userInfo = json_decode(Auth::guard('api')->user(),true);

        // 不带参的uri
        $this->uri = $request->route()->uri;

        // 记录日志
        $this->logRequest($request);

    }

    /**
     * 记录具体用户请求的接口与请求数据
     * @param Request $request
     */
    protected function logRequest(Request $request)
    {
        // 请求的方式
        $methods = $request->route()->methods;
        // 拼接methods
        $methodStr = implode(',', $methods);
        // 记录请求日志
        Log::channel('response')->info("请求:({$this->userInfo['name']})<{$this->uri}>{$methodStr}", ['params'=>$this->all]);
    }

    /**
     * 返回json格式的数据，此方法会走框架的后续处理
     * @param int $code | 0 为正确 -1为返回错误
     * @param string $msg | 返回的信息 success 表示成功返回
     * @param array $param | 需要额外增加的字段
     * @return \Illuminate\Http\JsonResponse
     */
    protected function setReturnJson(int $code, string $msg = 'ok', array $param = [])
    {
        $this->return = ["code" => $code, "msg" => $msg, "data" => $param];
        $this->logResponse();
        return response()->json($this->return);
    }

    /**
     * 记录接口返回日志
     */
    private function logResponse(){
        // 过滤不需要记录的日志
        if (!in_array($this->uri, $this->returnLogFliters)) {
            Log::channel('response')->info("返回:({$this->userInfo['name']})<{$this->uri}>", $this->return);
        }
    }


}
